﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Common;
using MarginTrading.Services;
using System.IO;


namespace MarginTrading.Forms
{
    public partial class SettlementsWnd : Form
    {
        double dFinalBuy = 0;
        double dFinalSell = 0;
        bool bTableDrawn = false;

        DateTime currentDate;

        public SettlementsWnd()
        {
            InitializeComponent();
        }

        private void SettlementsWnd_Load(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Maximized;
        }

        private void SettlementsWnd_SizeChanged(object sender, EventArgs e)
        {
            dataGridViewBuy.Width = (Size.Width - 75) / 2;
            dataGridViewBuy.Height = Size.Height - 250;
            dataGridViewBuy.Left = 20;

            dataGridViewSell.Width = (Size.Width - 75) / 2;
            dataGridViewSell.Height = Size.Height - 250;
            dataGridViewSell.Left = dataGridViewSell.Width + 40;

            int iClearance = 80;
            labelTotalSell.Top = dataGridViewSell.Bottom + 10;
            labelTotalSellFee.Top = dataGridViewSell.Bottom + 30;
            labelFinalSell.Top = dataGridViewSell.Bottom + 50;
            labelTotalBuy.Top = dataGridViewSell.Bottom + 10;
            labelTotalBuyFee.Top = dataGridViewSell.Bottom + 30;
            labelFinalBuy.Top = dataGridViewSell.Bottom + 50;

            labelSumTotalSell.Top = dataGridViewSell.Bottom + 10;
            labelSumTotalSellFee.Top = dataGridViewSell.Bottom + 30;
            labelSumFinalSell.Top = dataGridViewSell.Bottom + 50;
            labelSumTotalBuy.Top = dataGridViewSell.Bottom + 10;
            labelSumTotalBuyFee.Top = dataGridViewSell.Bottom + 30;
            labelSumFinalBuy.Top = dataGridViewSell.Bottom + 50;

            labelSumTotalSell.Left = dataGridViewSell.Left;
            labelTotalSell.Left = dataGridViewSell.Left + 150;
            labelSumTotalSellFee.Left = dataGridViewSell.Left;
            labelTotalSellFee.Left = dataGridViewSell.Left + 150;
            labelSumFinalSell.Left = dataGridViewSell.Left;
            labelFinalSell.Left = dataGridViewSell.Left + 150;

            labelSumTotalBuy.Left = dataGridViewBuy.Left;
            labelTotalBuy.Left = dataGridViewBuy.Left + 150;
            labelSumTotalBuyFee.Left = dataGridViewBuy.Left;
            labelTotalBuyFee.Left = dataGridViewBuy.Left + 150;
            labelSumFinalBuy.Left = dataGridViewBuy.Left;
            labelFinalBuy.Left = dataGridViewBuy.Left + 150;

            buttonSellSettle.Top = Height - iClearance;
            buttonSellSettle.Left = (Width - buttonSellSettle.Width - 10) / 2;
            labelBuySide.Top = dataGridViewBuy.Top - 20;
            labelSellSide.Top = dataGridViewSell.Top - 20;
            labelBuySide.Left = dataGridViewBuy.Left + ((dataGridViewBuy.Width - labelBuySide.Width) / 2);
            labelSellSide.Left = dataGridViewSell.Left + ((dataGridViewSell.Width - labelSellSide.Width) / 2);

            if (bTableDrawn)
            {
                dataGridViewSell.Columns[0].Width = 120;
                dataGridViewSell.Columns[1].Width = 75;
                dataGridViewSell.Columns[2].Width = 50;
                dataGridViewSell.Columns[3].Width = 70;
                dataGridViewSell.Columns[4].Width = 50;
                dataGridViewSell.Columns[5].Width = dataGridViewSell.Width - 367;

                dataGridViewBuy.Columns[0].Width = 120;
                dataGridViewBuy.Columns[1].Width = 75;
                dataGridViewBuy.Columns[2].Width = 50;
                dataGridViewBuy.Columns[3].Width = 70;
                dataGridViewBuy.Columns[4].Width = 50;
                dataGridViewBuy.Columns[5].Width = dataGridViewBuy.Width - 367;
            }
        }

        private void buttonGO_Click(object sender, EventArgs e)
        {



            int iCount = dataGridViewSell.Columns.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                dataGridViewSell.Columns.RemoveAt(0);
            }

            iCount = dataGridViewBuy.Columns.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                dataGridViewBuy.Columns.RemoveAt(0);
            }

            currentDate = dateTimePicker.Value;

            try
            {
                dataGridViewBuy.DataSource = DailyTransactionsServices.GetSettlementDataTable(dateTimePicker.Value, "B", false);
                dataGridViewSell.DataSource = DailyTransactionsServices.GetSettlementDataTable(dateTimePicker.Value, "S", false);

                for (int iI = 0; iI < dataGridViewBuy.Columns.Count; iI++)
                {
                    dataGridViewBuy.Columns[iI].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                for (int iI = 0; iI < dataGridViewSell.Columns.Count; iI++)
                {
                    dataGridViewSell.Columns[iI].SortMode = DataGridViewColumnSortMode.NotSortable;
                }
                dataGridViewBuy.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                dataGridViewSell.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                dataGridViewBuy.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                dataGridViewSell.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                dataGridViewBuy.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                dataGridViewSell.Columns[5].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;

                bTableDrawn = true;

                double dBuyTotal = 0;
                double dTotalBuyFee = 0;
                dFinalBuy = 0;

                double dSellTotal = 0;
                double dTotalSellFee = 0;
                dFinalSell = 0;

                iCount = dataGridViewBuy.Rows.Count;
                for (int iI = 0; iI < iCount; iI++)
                {
                    dBuyTotal += double.Parse(dataGridViewBuy.Rows[iI].Cells[3].Value.ToString());
                    dTotalBuyFee += double.Parse(dataGridViewBuy.Rows[iI].Cells[4].Value.ToString());
                    dFinalBuy += double.Parse(dataGridViewBuy.Rows[iI].Cells[5].Value.ToString());
                }

                iCount = dataGridViewSell.Rows.Count;
                for (int iI = 0; iI < iCount; iI++)
                {
                    dSellTotal += double.Parse(dataGridViewSell.Rows[iI].Cells[3].Value.ToString());
                    dTotalSellFee += double.Parse(dataGridViewSell.Rows[iI].Cells[4].Value.ToString());
                    dFinalSell += double.Parse(dataGridViewSell.Rows[iI].Cells[5].Value.ToString());
                }

                labelTotalSell.Text = String.Format("{0:0.00}", dSellTotal);//dSellTotal.ToString();
                labelTotalSellFee.Text = String.Format("{0:0.00}", dTotalSellFee);//dTotalSellFee.ToString();
                labelFinalSell.Text = String.Format("{0:0.00}", dFinalSell);//dFinalSell.ToString();

                labelTotalBuy.Text = String.Format("{0:0.00}", dBuyTotal); //dBuyTotal.ToString();
                labelTotalBuyFee.Text = String.Format("{0:0.00}", dTotalBuyFee);// dTotalBuyFee.ToString();
                labelFinalBuy.Text = String.Format("{0:0.00}", dFinalBuy); //dFinalBuy.ToString();
            }
            catch (System.Exception ex)
            {
            	
            }            

            //for (int iI = 0; iI < dataGridViewBuy.Rows.Count; iI++)
            //{
            //    dataGridViewBuy.Rows[iI].Cells[0].Value = true;
            //    fBuyTotal += double.Parse(dataGridViewBuy.Rows[iI].Cells[4].Value.ToString());
            //    labelBuyTotal.Text = String.Format("{0:0.00}", fBuyTotal); //fBuyTotal.ToString();
            //}
            //for (int iI = 0; iI < dataGridViewSell.Rows.Count; iI++)
            //{
            //    dataGridViewSell.Rows[iI].Cells[0].Value = true;
            //    fSellTotal += double.Parse(dataGridViewSell.Rows[iI].Cells[4].Value.ToString());
            //    labelSellTotal.Text = String.Format("{0:0.00}", fSellTotal);
            //}

            SettlementsWnd_SizeChanged(null, null);
        }

        private void ResetTables()
        {
            dateTimePicker.Value = currentDate;
            buttonGO_Click(null, null);
        }

        private string GetReferenceCode(string sType)
        {
            return sType + "-" + Program.GetNextSeqNO().ToString();
        }

        private void labelTotalBuy_Click(object sender, EventArgs e)
        {

        }

        private void buttonSellSettle_Click(object sender, EventArgs e)
        {
            //CreateSettlementFile();
            //return;
            DialogResult result = MessageBox.Show("Are you sure you want to proceed?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);

            if (result != DialogResult.OK)
            {
                return;
            }

            String sControlAccount;
            double dCusFee = 0;

            try
            {
                Config c = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_CONTROL_ACCOUNT);
                sControlAccount = c.Value;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Failed to find control account. Please check configurations", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            StringBuilder clientIDs = new StringBuilder();
            string sFileName = "Settlement_Data" + currentDate.ToLongDateString() + Program.GetNextSeqNO().ToString();
            bool bFailed = false;
            string sError = "";
            bool bSettled = false;
            int iCount = dataGridViewBuy.Rows.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                string clientCode = dataGridViewBuy.Rows[iI].Cells[0].Value.ToString();
                try
                {
                    Client c = ClientService.GetClientByCode(clientCode);
                    if (c.BankAccNo == "")
                    {
                        MessageBox.Show("Client " + c.Code + " does not have an account number");
                        break;
                    }

                    string sReferenceNO = GetReferenceCode("PA");
                    
                    LoanAccount accountEntry = new LoanAccount();

                    double dAmount = double.Parse(dataGridViewBuy.Rows[iI].Cells[5].Value.ToString());

                    accountEntry.Amount = double.Parse(dataGridViewBuy.Rows[iI].Cells[3].Value.ToString());
                    accountEntry.ReferenceNo = sReferenceNO;
                    accountEntry.ClientCode = clientCode;
                    accountEntry.CreatedDate = DateTime.Today;
                    accountEntry.EntryType = "PA";
                    accountEntry.TrParticulars = "Receipt on Sales"; //Ravin1
                    accountEntry.Remarks = "Receipt on Sales"; //Ravin1

                    string sTranDate = DailyTransactionsServices.Settle(clientCode, currentDate, "B", sReferenceNO, accountEntry);

                    bSettled = true;

                    string sRef = "Buy " + sTranDate;
                    String Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        c.BankAccNo, "D", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);

                    sRef = c.BankAccNo + " " + sTranDate.Substring(0, 5);
                    //sRef = c.BankAccNo;
                    if (sRef.Length > 20)
                    {
                        sRef = sRef.Substring(0, 20);
                    }
                    Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        sControlAccount, "C", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);
                }
                catch (System.Exception ex)
                {
                    bFailed = true;
                    sError += ex.Message;
                }
            }

            iCount = dataGridViewSell.Rows.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                string clientCode = dataGridViewSell.Rows[iI].Cells[0].Value.ToString();
                try
                {
                    Client c = ClientService.GetClientByCode(clientCode);
                    if (c.BankAccNo == "")
                    {
                        MessageBox.Show("Client " + c.Code + " does not have an account number");
                        break;
                    }

                    string sReferenceNO = GetReferenceCode("RC");

                    LoanAccount accountEntry = new LoanAccount();

                    double dAmount = double.Parse(dataGridViewSell.Rows[iI].Cells[5].Value.ToString());

                    accountEntry.Amount = double.Parse(dataGridViewSell.Rows[iI].Cells[3].Value.ToString());
                    accountEntry.ReferenceNo = sReferenceNO;
                    accountEntry.ClientCode = clientCode;
                    accountEntry.CreatedDate = DateTime.Today;
                    accountEntry.EntryType = "RC";
                    accountEntry.TrParticulars = "Payment on Purchases"; //Ravin1
                    accountEntry.Remarks = "Payment on Purchases"; //Ravin1

                    accountEntry.Amount *= -1;

                    string sTranDate = DailyTransactionsServices.Settle(clientCode, currentDate, "S", sReferenceNO, accountEntry);

                    bSettled = true;

                    string sRef = "Sell " + sTranDate;
                    String Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        c.BankAccNo, "C", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);

                    sRef = c.BankAccNo + " " + sTranDate.Substring(0, 5);
                    //sRef = c.BankAccNo;
                    if (sRef.Length > 20)
                    {
                        sRef = sRef.Substring(0, 20);
                    }
                    Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        sControlAccount, "D", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);
                    
                }
                catch (System.Exception ex)
                {
                    bFailed = true;
                    sError += ex.Message;
                }
            }

            if (bFailed)
            {
                MessageBox.Show("Updating database failed. Error: " + sError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (bSettled)
            {
                string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MarginTrading");
                Directory.CreateDirectory(path);
                path = Path.Combine(path, sFileName + ".txt");

                bool bWritten = false;
                try
                {
                    StreamWriter outfile = new StreamWriter(path);

                    using (outfile)
                    {
                        outfile.Write(clientIDs.ToString());
                        bWritten = true;
                    }
                }
                catch (System.Exception exc)
                {
                    MessageBox.Show("Failed to create settlement file. Error: " + exc.Message,
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                MessageBox.Show("Settling successful");

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Text Files|*.txt";
                saveFileDialog1.Title = "Save Settled Selection";
                saveFileDialog1.FileName = sFileName;
                saveFileDialog1.ShowDialog();

                if (saveFileDialog1.FileName != "")
                {
                    using (StreamWriter outfile = new StreamWriter(saveFileDialog1.FileName))
                    {
                        outfile.Write(clientIDs.ToString());
                    }
                }
            }
            else
            {
                MessageBox.Show("Nothing selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            ResetTables();

            //BuySettlementSummary buySettlementSummary = new BuySettlementSummary(comboBoxAgentCode.Text, dateTimePicker.Value);
            //buySettlementSummary.Show();
        }

        private void CreateSettlementFile()
        {
            String sControlAccount;

            try
            {
                Config c = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_CONTROL_ACCOUNT);
                sControlAccount = c.Value;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Failed to find control account. Please check configurations", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            StringBuilder clientIDs = new StringBuilder();
            string sFileName = "Settlement_Data" + currentDate.ToLongDateString() + Program.GetNextSeqNO().ToString();
            bool bFailed = false;
            string sError = "";
            bool bSettled = false;

            DataTable dtbuy = DailyTransactionsServices.GetSettlementDataTable(dateTimePicker.Value, "B", true);
            DataTable dtsell = DailyTransactionsServices.GetSettlementDataTable(dateTimePicker.Value, "S", true);

            int iCount = dtbuy.Rows.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                string clientCode = dtbuy.Rows[iI].ItemArray[0].ToString();// dataGridViewBuy.Rows[iI].Cells[0].Value.ToString();
                try
                {
                    Client c = ClientService.GetClientByCode(clientCode);
                    if (c.BankAccNo == "")
                    {
                        MessageBox.Show("Client " + c.Code + " does not have an account number");
                        break;
                    }

                    //string sReferenceNO = GetReferenceCode("PA");

                    //LoanAccount accountEntry = new LoanAccount();

                    double dAmount = double.Parse(dtbuy.Rows[iI].ItemArray[5].ToString());// dataGridViewBuy.Rows[iI].Cells[5].Value.ToString());

                    //accountEntry.Amount = double.Parse(dataGridViewBuy.Rows[iI].Cells[3].Value.ToString());
                    //accountEntry.ReferenceNo = sReferenceNO;
                    //accountEntry.ClientCode = clientCode;
                    //accountEntry.CreatedDate = DateTime.Today;
                    //accountEntry.EntryType = "PA";
                    //accountEntry.TrParticulars = "Receipt on Sales"; //Ravin1
                    //accountEntry.Remarks = "Receipt on Sales"; //Ravin1

                    string sTranDate = DailyTransactionsServices.GetTranDate(currentDate, clientCode);//Settle(clientCode, currentDate, "B", sReferenceNO, accountEntry);

                    //bSettled = true;

                    string sRef = "Buy " + sTranDate;
                    String Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        c.BankAccNo, "D", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);

                    sRef = c.BankAccNo + " " + sTranDate.Substring(0, 5);
                    if (sRef.Length > 20)
                    {
                        sRef = sRef.Substring(0, 20);
                    }
                    Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        sControlAccount, "C", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);
                }
                catch (System.Exception ex)
                {
                    bFailed = true;
                    sError += ex.Message;
                }
            }

            iCount = dtsell.Rows.Count;
            for (int iI = 0; iI < iCount; iI++)
            {
                string clientCode = dtsell.Rows[iI].ItemArray[0].ToString();
                try
                {
                    Client c = ClientService.GetClientByCode(clientCode);
                    if (c.BankAccNo == "")
                    {
                        MessageBox.Show("Client " + c.Code + " does not have an account number");
                        break;
                    }

                    //string sReferenceNO = GetReferenceCode("RC");

                    //LoanAccount accountEntry = new LoanAccount();

                    double dAmount = double.Parse(dtsell.Rows[iI].ItemArray[5].ToString());

                    //accountEntry.Amount = double.Parse(dataGridViewSell.Rows[iI].Cells[3].Value.ToString());
                    //accountEntry.ReferenceNo = sReferenceNO;
                    //accountEntry.ClientCode = clientCode;
                    //accountEntry.CreatedDate = DateTime.Today;
                    //accountEntry.EntryType = "RC";
                    //accountEntry.TrParticulars = "Payment on Purchases"; //Ravin1
                    //accountEntry.Remarks = "Payment on Purchases"; //Ravin1

                    //accountEntry.Amount *= -1;

                    string sTranDate = DailyTransactionsServices.GetTranDate(currentDate, clientCode);

                    bSettled = true;

                    string sRef = "Sell " + sTranDate;
                    String Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        c.BankAccNo, "C", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);

                    sRef = c.BankAccNo + " " + sTranDate.Substring(0, 5);
                    //sRef = c.BankAccNo;
                    if (sRef.Length > 20)
                    {
                        sRef = sRef.Substring(0, 20);
                    }
                    Line = String.Format("{0,-16}{1,1}{2,17}{3,81}{4,-20}",
                        sControlAccount, "D", String.Format("{0:0.00}", dAmount), "", sRef);

                    clientIDs.AppendLine(Line);

                }
                catch (System.Exception ex)
                {
                    bFailed = true;
                    sError += ex.Message;
                }
            }

            if (bFailed)
            {
                MessageBox.Show("Operation failed. Error: " + sError, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (bSettled)
            {
                string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MarginTrading");
                Directory.CreateDirectory(path);
                path = Path.Combine(path, sFileName + ".txt");

                bool bWritten = false;
                try
                {
                    StreamWriter outfile = new StreamWriter(path);

                    using (outfile)
                    {
                        outfile.Write(clientIDs.ToString());
                        bWritten = true;
                    }
                }
                catch (System.Exception exc)
                {
                    MessageBox.Show("Failed to create settlement file. Error: " + exc.Message,
                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Text Files|*.txt";
                saveFileDialog1.Title = "Save Settled Selection";
                saveFileDialog1.FileName = sFileName;
                saveFileDialog1.ShowDialog();

                if (saveFileDialog1.FileName != "")
                {
                    using (StreamWriter outfile = new StreamWriter(saveFileDialog1.FileName))
                    {
                        outfile.Write(clientIDs.ToString());
                    }
                }
            }
            else
            {
                MessageBox.Show("No entries found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void buttonRegenerate_Click(object sender, EventArgs e)
        {
            currentDate = dateTimePicker.Value;

            CreateSettlementFile();
        }
    }
}
